package com.fvision.camera.view.activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fvision.camera.BuildConfig;
import com.fvision.camera.R;
import com.fvision.camera.base.BaseActivity;
import com.fvision.camera.bean.FileBean;
import com.fvision.camera.manager.CmdManager;
import com.fvision.camera.util.Cmd_Const;
import com.fvision.camera.utils.CameraStateUtil;
import com.fvision.camera.utils.Const;
import com.fvision.camera.utils.LogUtils;
import com.fvision.camera.utils.ToastUtils;
import com.fvision.camera.view.fragment.VideoListFragment;
import com.huiying.cameramjpeg.UvcCamera;

import java.io.File;

import v4.FileProvider;

/**
 * 回放界面
 */
public class PlaybackActivity extends BaseActivity implements VideoListFragment.OnListFragmentInteractionListener,View.OnClickListener {

    public static final int REQUEST_VIDEO_PLAY = 11;
    private TextView recordnormal;
    private TextView recordlock;
    private FrameLayout content;
    private LinearLayout activityplayback;

    private VideoListFragment fragment_normal,fragment_lock,fragment_photo;
    private ImageView back;
    private TextView takepicture;

    private View rootview;
    private long length;
    private byte[] files = null;
    int i = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d("PlaybackActivity " + CmdManager.getInstance().getCurrentState().toString());
        resetPreview(rootview);
        loadFile();
//        LogUtils.d(CameraStateUtil.bytesToHexString(BaseApplication.cameraState.getStateFrame()));
//        initView();
//        initListener();
        initProgressDialog();

//        showLoadingDialog();
        if(UvcCamera.getInstance().isInit()){
//            initData();
            initVideo();
        }else{
//            Toast.makeText(PlaybackActivity.this,"摄像头未连接",Toast.LENGTH_LONG).show();
//            dismisLoadingDialog();
            if(!isFinishing())
            finish();
        }

//        CameraStateIml.getInstance().setOnCameraStateListner(new ICameraStateChange() {
//            @Override
//            public void stateChange() {
//                CameraStateBean state = CmdManager.getInstance().getCurrentState();
//                if(state.isCam_plist_state()){
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            ToastUtils.showLongToast(getApplicationContext(),"数据刷新了 "+i);
//                            i++;
//                            fragment_normal.resrefh();
//                        }
//                    });
//                }
//            }
//        });
    }



    public byte[] loadFile(){
        int fileSize = CmdManager.getInstance().getCurrentState().getFile_index();
        boolean isPlistState = CmdManager.getInstance().getCurrentState().isCam_plist_state();
        LogUtils.e(" isPlistState "+isPlistState);
        if(fileSize < 0 && !isPlistState){
  //          LogUtils.e(" fileSize2 "+fileSize);
//            Toast.makeText(getApplicationContext(),"获取文件数错误! fileSize = "+fileSize,Toast.LENGTH_LONG).show();
            finish();
            return null;
        }

 //       LogUtils.e(" fileSize3 "+fileSize);
        files = new byte[fileSize * 6];
        CmdManager.getInstance().getFiles(files);
        LogUtils.d("PlaybackActivity  fileByte "+ CameraStateUtil.bytesToHexString(files));
//        ToastUtils.showLongToast(getApplication(),"fileSize "+fileSize);
        return files;
    }

    @Override
    protected  void initView(){
        this.takepicture = (TextView) findViewById(R.id.take_picture);
        this.back = (ImageView) findViewById(R.id.back);
        this.activityplayback = (LinearLayout) findViewById(R.id.activity_playback);
        this.content = (FrameLayout) findViewById(R.id.content);
        this.recordlock = (TextView) findViewById(R.id.record_lock);
        this.recordnormal = (TextView) findViewById(R.id.record_normal);
        this.rootview=findViewById(R.id.rootview);
    }

    @Override
    protected  void initListener(){
        recordlock.setOnClickListener(this);
        recordnormal.setOnClickListener(this);
        takepicture.setOnClickListener(this);

        findViewById(R.id.back).setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_playback;
    }

    @Override
    protected void init() {

    }

    private void initVideo(){
        fragment_normal= VideoListFragment.newInstance(files, Cmd_Const.FILE_TYPE_VIDEO);
        fragment_lock=VideoListFragment.newInstance(files,Cmd_Const.FILE_TYPE_LOCK);
        fragment_photo=VideoListFragment.newInstance(files,Cmd_Const.FILE_TYPE_PICTURE);
//        getSupportFragmentManager().beginTransaction().add(R.id.content, fragment_lock).commit();
//        getSupportFragmentManager().beginTransaction().add(R.id.content, fragment_normal).commit();
//        showFragment(fragment_normal);
        recordnormal.performClick();
    }

    private VideoListFragment mCurrentFragment;
    private void showFragment(Fragment fragment){
        mCurrentFragment = (VideoListFragment) fragment;
        getFragmentManager().beginTransaction().replace(R.id.content,fragment).commit();
    }

    @Override
    public void onListFragmentInteraction(FileBean item) {
        if(item.fileType == Cmd_Const.FILE_TYPE_LOCK || item.fileType == Cmd_Const.FILE_TYPE_VIDEO) {
            Intent playfile = new Intent(PlaybackActivity.this,VideoPlayActivity.class);
            playfile.putExtra(VideoPlayActivity.KEY_FILEBEAN,item);
            startActivityForResult(playfile,REQUEST_VIDEO_PLAY);
        }else if(item.fileType == Cmd_Const.FILE_TYPE_PICTURE){
//            Intent intent = new Intent();
//            intent.setAction(android.content.Intent.ACTION_VIEW);
//            intent.setDataAndType(Uri.fromFile(new File(Const.JPG_PATH+item.fileName)), "image/*");
//            startActivity(intent);
            File apkFile = new File(Const.JPG_PATH+item.fileName);
            Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
                intent.setDataAndType(contentUri, "image/*");
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), "image/*");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            startActivity(intent);
//v4注释
            //v4注释 注释下面代码使用v4
//            Intent previewphoto=new Intent(PlaybackActivity.this,ImagePreviewActivity.class);
//            ArrayList<String> imgList = new ArrayList<>();
//            for(FileBean bean:fragment_photo.getFileList()){
//                imgList.add(Const.JPG_PATH+bean.fileName);
//            }
//            previewphoto.putStringArrayListExtra(ImagePreviewActivity.KEY_FILEBEANS, imgList);
//            previewphoto.putExtra(ImagePreviewActivity.KEY_POSITION,fragment_photo.getFileList().indexOf(item));
//            startActivity(previewphoto);

        }
    }

    @Override
    public void onDownLoad(final FileBean item) {
        if(null!=item){
            new Thread(new Runnable() {
                @Override
                public void run() {
                 //   downloadFile(item);
                }
            }).start();
        }
    }

    @Override
    public void onDelete(FileBean item) {
        if (mCurrentFragment != null) {
            mCurrentFragment.showDeleteFile(item);
        }
    }

    private ProgressDialog mProgressDialog;

    private void initProgressDialog(){
        mProgressDialog=new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setMax(100);
    }

    private void showProgress(int progress){
        Log.e("ondownloading","progress="+progress);
        if(null==mProgressDialog)return;
        mProgressDialog.setProgress(progress);
        mProgressDialog.show();
    }

    private void hideProgress(){
        if(null==mProgressDialog)return;
        mProgressDialog.dismiss();
    }

    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    showProgress(msg.arg1);
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.record_normal:
                showFragment(fragment_normal);
//                recordnormal.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
//                recordlock.setBackgroundColor(getResources().getColor(android.R.color.white));
//                takepicture.setBackgroundColor(getResources().getColor(android.R.color.white));
                recordnormal.setSelected(true);
                recordlock.setSelected(false);
                takepicture.setSelected(false);
                break;
            case R.id.record_lock:
                showFragment(fragment_lock);
//                recordlock.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
//                recordnormal.setBackgroundColor(getResources().getColor(android.R.color.white));
//                takepicture.setBackgroundColor(getResources().getColor(android.R.color.white));
                recordnormal.setSelected(false);
                recordlock.setSelected(true);
                takepicture.setSelected(false);
                break;
            case R.id.take_picture:
                showFragment(fragment_photo);
//                takepicture.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
//                recordlock.setBackgroundColor(getResources().getColor(android.R.color.white));
//                recordnormal.setBackgroundColor(getResources().getColor(android.R.color.white));
                recordnormal.setSelected(false);
                recordlock.setSelected(false);
                takepicture.setSelected(true);
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case REQUEST_VIDEO_PLAY:
                boolean isLock = false;
                FileBean bean = null;
                if(data!=null){
                    isLock = data.getBooleanExtra(VideoPlayActivity.KEY_IS_LOCK,false);
                    bean = (FileBean)data.getSerializableExtra(VideoPlayActivity.KEY_FILE_BEAN);
                }

                if(isLock){
                    ToastUtils.showLongToast(getApplicationContext(),getString(R.string.video_moved_to_lock));
                    loadFile();
                    fragment_normal.delItem(bean.fileName);
                    bean.fileName = bean.fileName.replace("MOV","LOK");
                    bean.fileType = Cmd_Const.FILE_TYPE_LOCK;
                    fragment_lock.addItem(bean);
                }
                break;
        }
    }
}
